package common;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

/**
 *    Comparable 接⼝实际上是出⾃java.lang包 它有⼀个 compareTo(Object obj) ⽅法⽤来排序
 *    Comparator 接⼝实际上是出⾃ java.util 包它有⼀个 compare(Object obj1, Object obj2) ⽅法⽤来排序
 *
 *    String 的 Comparable方法实现逻辑
 *
 *
 *          //  String 比较的是每个字符的大小，既使用String的CompareTo 方法比较S1="abc"和S2="abd", 那么S2>S1  因为d>c,如果字符一样，那么就比较他们的长度。那个字符串长那个就大
 *          public int compareTo(String anotherString) {
 *              int len1 = value.length;
 *              int len2 = anotherString.value.length;
 *              int lim = Math.min(len1, len2);
 *              char v1[] = value;
 *              char v2[] = anotherString.value;
 *
 *              int k = 0;
 *              while (k < lim) {
 *                  char c1 = v1[k];
 *                  char c2 = v2[k];
 *                  if (c1 != c2) {
 *                     return c1 - c2;
 *                 }
 *                  k++;
 *              }
 *               return len1 - len2;
 *         }
 *
 *     Integer 的 Comparable方法实现逻辑
 *
 *          public int compareTo(Integer anotherInteger) {
 *             return compare(this.value, anotherInteger.value);
 *         }
 *
 *        // x:当前类，y:其他类  算法：x<y :  返回 -1
 *                                   x=y :  返回  0
 *                                   x>y :  返回  1
 *
 *        public static int compare(int x, int y) {
 *         return (x < y) ? -1 : ((x == y) ? 0 : 1);
 *     }
 *
 *
 *
 */
public class Comparable_Comparator {
     @Test
     public void test1(){
         ArrayList<Integer> arrayList = new ArrayList<>();
         arrayList.add(-1);
         arrayList.add(3);
         arrayList.add(3);
         arrayList.add(-5);
         arrayList.add(7);
         arrayList.add(4);
         arrayList.add(-9);
         arrayList.add(-7);
         System.out.println("原始数组:");
         System.out.println(arrayList);
         // void reverse(List list)：反转
         Collections.reverse(arrayList);
         System.out.println("Collections.reverse(arrayList):");
         System.out.println(arrayList);
         // void sort(List list),按⾃然排序的升序排序
         Collections.sort(arrayList);
         System.out.println("Collections.sort(arrayList):");
         System.out.println(arrayList);
         // 定制排序的⽤法
         Collections.sort(arrayList, Comparator.reverseOrder());
         System.out.println("定制排序后：");
         System.out.println(arrayList);
     }
    /**
     *   a : 97
     *   b : 98
     *   c : 99
     *     .
     *     .
     *     .
     *   z : 122
     */

    @Test
    public void test(){

        Character[] str=new Character[]{'a','b','c','d','e','f','d','e','f','g','z'};
        for(int i=0;i<str.length;i++){
            System.out.println(str[i]+1-1);
        }
    }
}
